package com.gitee.kamismile.gatewayAgent.client.handler;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import com.gitee.kamismile.gatewayAgent.protobuf.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by win7 on 2016/10/30.
 */
public class ClientHeartBeatHandler extends ChannelDuplexHandler {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (!(evt instanceof IdleStateEvent)) {
            super.userEventTriggered(ctx, evt);
            return;
        }
        if (evt instanceof IdleStateEvent) {
            Message.RouterMessage.Builder msg = Message.RouterMessage.newBuilder();

            Message.RouterRequest.Builder request = Message.RouterRequest.newBuilder();
            request.setSeq(0L);
            request.setRouter("0");
            Message.Command.Builder cmd = Message.Command.newBuilder();
            cmd.setCommand("client@connect@heart");
            request.setCmd(cmd);

            msg.addRequest(request);
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
//                logger.info("[发送心跳探测消息READER_IDLE][" + message.toString().trim() + "]");
                ctx.writeAndFlush(msg);
            } else if (e.state() == IdleState.WRITER_IDLE) {
//                logger.info("[发送心跳探测消息WRITER_IDLE][" + message.toString().trim() + "]");
                ctx.writeAndFlush(msg);
            } else if (e.state() == IdleState.ALL_IDLE) {
                ctx.writeAndFlush(msg);
            }
        }
    }


}
